﻿using System;
using System.Collections.Generic;
using UnityEngine;

namespace Elvex
{
    public class Area
    {
        // 中心
        public Vector3 Center { get; }
        
        // 宽
        public float Width { get; }

        // 高
        public float Height { get; }       

        public Area(Vector3 center, float width, float height)
        {
            Center = center;
            Width = width;
            Height = height;
        }
    }

    public static class UIUtility
    {
        public static void GetArea(this Canvas canvas, RectTransform target, out Area area)
        {
            Vector3[] targetCorners = new Vector3[4];//存储要镂空组件的四个角的数组
            Vector3 center = Vector3.zero;     // 镂空区域的中心
            float width;        // 镂空区域的宽
            float height;       // 镂空区域的高

            // 获取中心点
            // GetWorldCorners:在世界空间中得到计算的矩形的角。参数角的数组
            target.GetWorldCorners(targetCorners);
            var canvasrect = canvas.GetComponent<RectTransform>();
            // 讲四个角的世界坐标转为局部坐标坐标
            for (int i = 0; i < targetCorners.Length; i++)
            {
                //把世界坐标转化为屏幕坐标
                Vector2 screenPoint = RectTransformUtility.WorldToScreenPoint(canvas.worldCamera, targetCorners[i]);

                // 屏幕坐标转换为局部坐标
                //out的是vector2类型，事先声明
                Vector2 localPoint;
                RectTransformUtility.ScreenPointToLocalPointInRectangle(canvasrect, screenPoint, canvas.worldCamera, out localPoint);
                targetCorners[i] = localPoint;
            }

            //计算中心点
            center.x = targetCorners[0].x + (targetCorners[3].x - targetCorners[0].x) / 2;
            center.y = targetCorners[0].y + (targetCorners[1].y - targetCorners[0].y) / 2;

            // 计算宽高
            width = (targetCorners[3].x - targetCorners[0].x) / 2;
            height = (targetCorners[1].y - targetCorners[0].y) / 2;
            area = new Area(center, width, height);
        }
    }
}
